<!--配送商端-销售管理-寄售补货需求订单列表-发货-->
<template>
  <div class="operation-return">
    <div
      class="top-info-box"
      v-loading="topLoading">
      <div
        class="top-info-item"
        v-for="(item,index) in deliverTopInfo"
        :key="index">
        <span class="text-left">{{ item.label }}</span>
        <span v-if="item.value=== 'orderStatus'">{{ status[deliverTopData[item.value]] }}</span>
        <span v-else>{{ deliverTopData[item.value] }}</span>
      </div>
    </div>
    <el-container class="container-box">
      <div class="btn-box">
        <el-button
          type="primary"
          size="mini"
          @click="handleImportDeliverGoodsDetail">
          <i class="el-icon-date" />
          导入发货详情
        </el-button>
        <el-button
          type="text"
          @click="handleDownloadTemplate">下载发货导入模板.cvs</el-button>
      </div>
      <!-- 数据列表 -->
      <el-editable
        class="table-box"
        :data="tableData.content"
        height="200"
        v-loading="tableLoading"
        :columns="deliverGoodsColumns"
        ref="deliveryTable"
      >
        <template
          slot="default-placeholder"
          slot-scope="scope">
          <el-editable
            class="inside-table-box"
            :data="scope.row.distributorList"
            height="400"
            v-loading="insideTableLoading"
            :columns="deliverGoodsColumnsInside"
          />
        </template>
        <template
          slot="default-sweepCount"
          slot-scope="scope">
          <span>{{ sweepCodeNum(scope.row) }}</span>
        </template>
        <!-- 操作 -->
        <template
          slot="default-action"
          slot-scope="scope">
          <el-button
            type="text"
            @click="toGoods(scope)">去发货</el-button>
        </template>
      </el-editable>
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="curPage"
        :page-sizes="PAGE_NUMBER"
        :page-size="pageSize"
        :layout="PAGINATION_LAYOUT"
        :total="totalElements"
      />
      <!-- 去发货弹窗 -->
      <deliver-dialog
        :show.sync="dialogSetting.visible"
        :current-selected-data="currentSelectedData"
        :callback="handleSubmitSuccess"
        @submitDialog="submitDelivery"
      />
    </el-container>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
import ElEditable from '@components/el-editable/index.vue'
import DeliverDialog from '@/moduleComponents/beforeSettle/distributorSide/salesManagement/deliverDialog'

import {
  DELIVER_TOP_INFO,
  DELIVER_GOODS_COLUMNS,
  PART_DETAIL_COLUMNS_INSIDE
} from './const.js'
import { isObject, cloneDeep, hasIn } from 'lodash'
import { PAGE_NUMBER, PAGINATION_LAYOUT } from '@const/common.js'
// import {  } from '@const/beforeSettleApi'
import {
  getTablefollById,
  followOrderDelivery,
  followOrderConfirmDelivery,
  getPageTableList,
  deliverAddress
} from '@const/beforeSettleApi'

export default {
  name: 'OperationReturn',
  components: { ElEditable, DeliverDialog },

  data () {
    return {
      deliverTopInfo: DELIVER_TOP_INFO,
      deliverTopData: {},
      // 列表配置信息
      tableLoading: false,
      topLoading: false,
      tableData: [],
      deliverGoodsColumns: DELIVER_GOODS_COLUMNS,
      insideTableLoading: false,
      deliverGoodsColumnsInside: PART_DETAIL_COLUMNS_INSIDE,
      // 发货弹窗信息
      dialogSetting: {
        visible: false
      },
      currentSelectedData: [],
      // 分页配置信息
      curPage: 1,
      PAGE_NUMBER,
      PAGINATION_LAYOUT,
      pageSize: PAGE_NUMBER[0],
      totalElements: 0,
      // 状态信息
      status: {
        0: '全部',
        1: '待确认',
        2: '待发货',
        3: '部分发货',
        4: '全部发货',
        5: '已完成',
        6: '已撤销',
        7: '待术后还回'
      },
      index: null
    }
  },
  computed: {
    id () {
      return this.$route.query.id
    },
    orderCode () {
      return this.$route.query.orderCode
    },
    isCanDeliverGoods () {
      return this.currentSelectedData.length < 1
    }
  },
  mounted () {
    this.initNavButtons()
    this.getDeliverTopData()
    this.getDeliverTableList()
  },
  methods: {
    toGoods (e) {
      this.index = e.$index
      let arr = []
      arr.push(e.row)
      this.currentSelectedData = arr
      this.dialogSetting.visible = true
    },
    // 已扫码数量
    sweepCodeNum (e) {
      let codeNum = 0
      let arr = e.distributorList || []
      arr.forEach(item => {
        codeNum += item.num
      })
      let data = codeNum + '/' + e.awaitSendNum + (e.unit || '')
      e.codeNum = codeNum
      return data
    },
    ...mapMutations(['changeLayoutHandle']),
    // 初始化 导航栏 按钮组
    initNavButtons () {
      const btn = {
        type: 'btn',
        arr: [
          {
            type: 'button',
            noReturn: true,
            val: '返回',
            handle: this.back
          },
          { type: 'primary', val: '确认发货', handle: this.handleNavBtnSubmit }
        ]
      }
      this.changeLayoutHandle(btn)
    },
    // 右上角确认按钮
    handleNavBtnSubmit () {
      // todo 跟台订单不能部分发货，所以要检验所有产品的待发货和已扫码一致，这里没有考虑分页，实际上需要重新获取一次所有产品再校验，产品设计不科学
      // const hasInsufficientCount = this.tableData.some(item => item.sweepCount !== item.awaitSendNum)
      // if (hasInsufficientCount) {
      //   this.$message.warning('所有产品的扫码数量需与待发货数量一致才能发货')
      //   return
      // }
      let isNum = 0
      this.tableData.forEach(item => {
        if (Number(item.codeNum) !== Number(item.awaitSendNum)) {
          isNum++
        }
      })
      if (isNum !== 0) {
        this.$message({ type: 'warning', message: '扫码数量必须等于待收货数量!' })
        return false
      }
      // 扫码信息
      let arr = this.tableData.map(item => ({
        orderItemId: item.id,
        sweepCount: item.codeNum,
        distributorList: item.distributorList
      }))
      // 参数
      let data = {
        purchaseOrderId: this.deliverTopData.needPurhcaseId,
        id: this.deliverTopData.id,
        productList: arr
      }

      this.$confirm('确认要收货吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.post(followOrderConfirmDelivery, data).then(res => {
          if (Number(res.data.code) === 0) {
            this.$message({
              type: 'success',
              message: '提交成功!'
            })
            this.back()
          }
        })
      })
    },
    handleImportDeliverGoodsDetail () {
      // 导入发货详情
    },
    handleDownloadTemplate () {
      // 下载模板
    },
    handletabs () {
      // tab
    },
    inputChange () {
      // 条码
    },
    handleSizeChange (size) {
      this.pageSize = size
      this.getDeliverTableList()
    },
    handleCurrentChange (curPage) {
      this.curPage = curPage
      this.getDeliverTableList()
    },
    getDeliverTopData () {
      this.topLoading = true
      this.$axios
        .post(`${getTablefollById}?id=${this.id}`)
        .then(({ data }) => {
          if (Number(data.code) !== 0) return
          this.deliverTopData = data.payload || {}
        })
        .catch(e => {})
        .finally(() => {
          this.topLoading = false
        })
    },
    // 获取列表数据
    getDeliverTableList () {
      this.tableLoading = true
      this.$axios
        .post(getPageTableList, {
          page: this.curPage,
          pageSize: this.pageSize,
          id: this.id
        })
        .then(({ data }) => {
          if (Number(data.code) !== 0) return
          this.tableData = hasIn(data, ['payload']) ? data.payload : []
          this.totalElements = data.payload.totalElements
        })
        .catch(e => {})
        .finally(() => {
          this.tableLoading = false
        })
    },
    submitDelivery (sweepCount, itemList) {
      const dateInfo = itemList.map((it, index) => {
        if (it.expDate < it.productDate) return index + 1
      })
      let hasIndex = dateInfo.filter(it => {
        return !(!it || it === '')
      })
      const awaitsendCount = this.currentSelectedData[0].awaitSendNum || 0
      if (itemList.length < 1) {
        this.$message.warning('请扫描或者手动添加物品详情')
        return false
      } else if (sweepCount > awaitsendCount) {
        this.$message.warning('扫码数量不能超过待收货数量')
        return false
      } else if (hasIndex.length > 0) {
        this.$message.warning(`第${hasIndex.join(',')}行有效期不能小于生产日期`)
        return false
      } else {
        this.tableData[this.index].distributorList = itemList
        this.dialogSetting.visible = false
      }
    },
    handleSubmitSuccess () {
      this.getDeliverTableList()
    },

    back () {
      this.$router.go(-1)
    }
  }
}
</script>

<style lang="less">
@import '../m-front-common/pc/assets/var.less';
@textColor: #26344c;
@grayColor: #a7b1c7;
@btnColor: #2371c5;
@white: #fff;

.operation-return {
  display: flex;
  flex-direction: column;
  .top-info-box {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;

    .top-info-item {
      width: 25%;
      font-size: @defaultFontSize;
      color: @textColor;
      font-weight: 400;
      padding-bottom: 20px;

      .text-left {
        color: @grayColor;
        padding-right: 10px;
        width: 120px;
        text-align: right;
        display: inline-block;
      }
    }
  }

  .container-box {
    display: flex;
    flex-direction: column;

    .btn-box {
      margin-bottom: 16px;
      display: flex;
      justify-content: right;
    }
    .table-box {
      flex: 1;
    }
    .handle-box {
      .dialog-table-box {
        margin-bottom: 20px;
      }

      .button-box {
        width: 167px;
        margin: 20px auto;
      }

      .submission {
        background: rgba(35, 113, 197, 1);
        border: 0;
        color: #fff;
        margin-bottom: 10px;
      }

      .topfrom {
        display: flex;
        flex-direction: row;
        justify-content: space-between;

        .el-form-item {
          display: inline-block;
        }

        .el-input {
          width: 297px;
        }
      }
    }

    .dialog-detail-title {
      padding: 0 0 16px 16px;
    }

    .pagination {
      padding-top: 10px;
      display: flex;
      justify-content: flex-end;
      padding-right: 0;
    }
  }
}
</style>
